<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !assetDetailInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="资产出库单明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button
            v-if="
              $permission('assetUseExportOrder:exportExcel') &&
              infoList.data.status === 3
            "
            @click="exportExcel"
            >导出excel</el-button
          >

          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button @click="recall" v-if="canRecall">撤回</el-button>
          <el-button @click="btnFlow('approve')" v-if="canAccept"
            >批准</el-button
          >
          <el-button @click="btnFlow('reject')" v-if="canReject"
            >驳回</el-button
          >
          <el-button @click="btnFlow('refuse')" v-if="canRefuse"
            >拒绝</el-button
          >
          <el-button @click="salesReview" v-if="canSalesReview">销审</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList" />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
                <template v-slot:col-assetAmortizationDeptValue="scope">
                  <template
                    v-if="
                      scope.row.assetUseDeptBusinessList &&
                      scope.row.assetUseDeptBusinessList.length
                    "
                  >
                    <span
                      v-for="(item, index) in scope.row
                        .assetUseDeptBusinessList"
                      :key="index"
                    >
                      {{ item.useDeptName }}-{{ item.rate }}
                      <span
                        v-show="
                          index < scope.row.assetUseDeptBusinessList.length - 1
                        "
                        >,</span
                      >
                    </span>
                  </template>
                  <template v-else>
                    <span> - </span>
                  </template>
                </template>
                <template v-slot:col-assetName="scope">
                  <span class="slip-edit" @click="showAssetDetail(scope.row)">{{
                    scope.row.assetName
                  }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <assetUseExportOrderModify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :export-id="modifyInfo.exportId"
    />
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>

<script setup name="AssetUseExportOrderDetail">
import {
  detailAssetUseExportOrder,
  exportExcelAssetUseExportOrder,
  getAssetUseExportPrint,
  assetUseExportOrderDetailsCustomizeListAll,
  submitAssetUseExportOrder,
  flushOrderDetail,
  revokeAssetUseExportOrder,
  salesReviewUseExportOrder,
  approvedAssetUseExportOrders,
  rejectAssetUseExportOrders,
  refuseAssetUseExportOrders,
} from '@/api/asset.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderOpAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)
const assetUseExportOrderModify = defineAsyncComponent(() => import('./modify'))

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'id', 'tableRow'])

const infoList = ref({
  data: {},
  fieldList: [
    { label: '出库单号', value: 'orderNo', type: 'text' },
    { label: '出库仓库', value: 'depotName', type: 'text' },
    // { label: '出库部门', value: 'deptName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '出库人', value: 'exportUserName', type: 'text' },
    { label: '出库时间', value: 'exportTime', type: 'text' },
    { label: '领用部门', value: 'useDeptName', type: 'text' },
    { label: '领用人', value: 'contactName', type: 'text' },
    { label: '领用人电话', value: 'phone', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    { label: '业务日期', value: 'businessDate', type: 'text' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.tableRow.id,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 65,
    orderId: props.id || props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:print') &&
    infoList.value.data.status === 3
  )
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:update') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 6)
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:submit') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 6)
  )
})
// 批准
const canAccept = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:approve') &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_use_export_approval == 1 &&
    infoList.value.data.status === 4
  )
})
// 驳回
const canReject = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:reject') &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_use_export_approval == 1 &&
    infoList.value.data.status === 4
  )
})
// 拒绝
const canRefuse = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:refuse') &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_use_export_approval == 1 &&
    infoList.value.data.status === 4
  )
})
// 撤回
const canRecall = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:recall') &&
    (infoList.value.data.status === 4 ||
      (infoList.value.data.status === 3 &&
        proxy.$store.state.permission.systemConfig
          .allow_assets_use_export_approval == 0))
  )
})
// 销审
const canSalesReview = computed(() => {
  return (
    proxy.$permission('assetUseExportOrder:salesReview') &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_use_export_approval != 0 &&
    infoList.value.data.status === 3
  )
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => modifyInfo.value.visible,
  (value) => {
    if (!value) {
      getMain()
      getList()
    }
  }
)

setData()
function setData() {
  let obj = {
    assetAmortizationDeptValue: {
      label: '使用部门',
      value: 'assetAmortizationDeptValue',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
//提交
function submit() {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'assetUseExport',
    orderIds: [infoList.value.data.id],
  }
  submitAssetUseExportOrder(data).then((resp) => {
    if (resp && resp.success) {
      if (resp.msgType === 'messageBox') {
        flushOrderDetail([infoList.value.data.id]).then()
      }
      getMain()
      getList()
    }
  })
}
// 按钮审批原因弹窗
function btnFlow(code) {
  const row = infoList.value.data
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approvedAssetUseExportOrders
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getMain()
        getList()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAssetUseExportOrders
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAssetUseExportOrders
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getMain()
          getList()
        }
      })
    })
}
// 撤回
function recall() {
  revokeAssetUseExportOrder([infoList.value.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getMain()
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview() {
  salesReviewUseExportOrder([infoList.value.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getMain()
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function showDetail(row) {
  individualInfo.value.visible = true
  individualInfo.value.info = row
  individualInfo.value.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: row.groupConcatIds,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.id || props.tableRow.id,
    },
  }
}
function getMain() {
  detailAssetUseExportOrder(props.id || props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
    }
  })
}
function getList() {
  assetUseExportOrderDetailsCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
      }
    }
  )
}

function update() {
  modifyInfo.value.exportId = infoList.value.data.id
  modifyInfo.value.title = '修改出库单'
  modifyInfo.value.visible = true
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetUseExportDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.id || props.tableRow.id,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id || props.tableRow.id,
      orderType: 64,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id || props.tableRow.id,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'assetUseExportOrderDetail-com.slip.spd.entity.vo.asset.AssetUseExportOrderDetailVO',
    orderIds: [props.id || props.tableRow.id],
  }
  getAssetUseExportPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
//导出excel
function exportExcel() {
  exportExcelAssetUseExportOrder(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'assetUseExportOrderDetail-com.slip.spd.entity.vo.asset.AssetUseExportOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
</script>

<style scoped></style>
